---
import Default from "@astrojs/starlight/components/SocialIcons.astro"
import Start from "../icons/start.astro"
import Github from "../icons/logos/github.astro";

const githubRepo = "https://github.com/carlosjorger/fluid-dnd"

---
<!-- TODO: add get github stars api https://github.com/formkit/drag-and-drop/blob/main/docs/server/api/stars.ts -->
<script>
    async function getGitHubStarsNoAuth(owner:string, repo:string  ) {
      if (typeof window === 'undefined') {
        return 0;
      }
      const cachedStars = localStorage.getItem("fluid-dnd-stars");
      const [lastAccessed, totalStars] = cachedStars
        ? cachedStars.split("|")
        : [0, 0];
      if (Date.now() - Number(lastAccessed) > 1000 * 60) {
        const response = await fetch(`https://api.github.com/repos/${owner}/${repo}`) 
        if (response.ok) {
          try {
            const data = (await response.json()) as { stargazers_count: number };
            localStorage.setItem("fluid-dnd-stars", `${Date.now()}|${data.stargazers_count}`);
            return data.stargazers_count;
          } catch (error) {
            console.error('Error fetching GitHub stars:', error);
            return null;
          }
        }
      }
      return Number(totalStars);

  }
  // Client-side fetch after component loads
  (async () => {
    const startCountElement = document.getElementById('star-count');
    if (!startCountElement) {
      return;
    }
    try {
      const startCount = await getGitHubStarsNoAuth('carlosjorger', 'fluid-dnd');
      if (startCount) {
        startCountElement.textContent = new Intl.NumberFormat().format(startCount);
      } 
    } catch (error) {
      startCountElement.textContent= 'Unavailable';
      console.error('Error fetching GitHub stars:', error);
    }
  })();
</script>
<a href={githubRepo} class="flex no-underline text-gray-700 dark:text-gray-300 items-center gap-2 pr-0 hover:opacity-65"><Start height="16" width="16" class="text-[#facc15]"/> <span id="star-count"></span> <Github class="text-accent-600 dark:text-accent-200" width="16" height="16"/></a>

<Default {...Astro.props}><slot /> </Default>
